package gradle.common.feign.config.annotation;

import gradle.common.core.constants.SecurityConstant;
import gradle.common.core.utils.ServletUtil;
import gradle.common.feign.config.exception.PermissionException;
import jakarta.servlet.http.HttpServletRequest;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * 权限认证切面
 *
 * @author 1141193930@qq.com
 */
@Aspect
@Component
public class PermissionAspect {


    /**
     * 是否包含某个权限
     */
    @Before("@annotation(hasPermission)")
    public void checkPermission(RequiredPermission hasPermission) {

        HttpServletRequest currentHttpRequest = ServletUtil.getCurrentHttpRequest();
        String authorities = currentHttpRequest.getHeader(SecurityConstant.AUTHORITIES);
        //权限不足异常
        if (Objects.isNull(authorities)) {
            throw new PermissionException();
        }
        //指定权限不包含在当前用户权限中，抛出权限不足异常
        if (!authorities.contains(hasPermission.value())) {
            throw new PermissionException();
        }
    }

}